package com.xfactor.poker;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;


public class Play {
	public static final int SEAT_INFO_MSG=0;
	public static final int INQUIRE_MSG=1;
	private static InetAddress tableIp;
	private static int tablePort;
	private static InetAddress playerIP;
	private static int playerPort;
	private static String playerID = "";
	private ServerSocket s;
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		try {
			tableIp  = InetAddress.getByName(args[0]);
			tablePort  = Integer.parseInt(args[1]);
			playerIP  = InetAddress.getByName(args[2]);
			playerPort  = Integer.parseInt(args[3]);
			playerID  = args[4];
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		Play play = new Play();
		play.register();
	}
	
	private void register(){
		FileWriter fw;
		BufferedWriter bw = null;
		try {
			File file = new File(
					"./send" + playerID);
			if (!file.exists()) {
				file.createNewFile();
			}
			fw = new FileWriter(file.getAbsoluteFile());
			bw = new BufferedWriter(fw);
			bw.write(new String("sending \n"));
			bw.flush();
			
            Socket socket =new Socket(tableIp, tablePort,playerIP,playerPort);  
            OutputStream os=socket.getOutputStream();  
            PrintWriter pw=new PrintWriter(os);  
            InputStream is=socket.getInputStream();  
            BufferedReader br=new BufferedReader(new InputStreamReader(is));  
            
            	String regMsg="reg: " +  playerID + " " + "holyfuck" + " \n"; 
                pw.write(regMsg);  
                pw.flush();  
                os.flush();
            
            String reply=null;  
            while(!((reply=br.readLine())==null)){  
            	bw.write(reply + "\n");
            	if(reply.indexOf("inquire/")!=-1){
            		bw.write("-------inquire-----------------\n");
                	String testMsg="all_in"+ " \n"; 
                     pw.write(testMsg);  
                     pw.flush();  
                     os.flush();
//                     socket.shutdownOutput();  
                }
            }  
            
            bw.flush();
            br.close();  
            is.close();  
            pw.close();  
            os.close();  
            socket.close(); 
			
			bw.close();
			
			
		} catch (Exception e) {
			// TODO Auto-generated catch block
			try {
				bw.write(e.getMessage());
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			e.printStackTrace();
			
		} 
	}
	
}
